var prefix = jsctx + "/channel/gain";

var channelGain = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                gainName: $('#gainName').val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listPageChannelGain",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageList: [10, 20, 30],
                pageSize: 10,
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                height: h,
                paginationShowPageGo: true,
                rightFixedColumns: false,
                queryParams: function (params) {
                    return {
                        pageNo: (params.offset / params.limit) + 1,
                        pageSize: params.limit,
                        gainName: $("#gainName").val(),
                    };
                },
                columns: [
                    {
                        field: 'number',
                        title: '序号',
                        width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'channelLevel', title: '渠道商等级', align: 'center'},
                    {field: 'gainName', title: '权益名称', align: 'center'},
                    {
                        field: 'gainLogo', title: '图标', align: 'center',
                        formatter: function (value, row, index) {
                            if (value != null && value != '') {
                                return "<img src=" + value + " width='50px' height='50px'>";
                            }
                        }
                    },
                    {field: 'gainExplain', title: '权益说明', align: 'center'},
                    {

                        field: 'status', title: '状态', width: '100', align: 'center',
                        formatter: function (value, row, index) {
                            if (row.channelLevel == 'S0') {
                                return '启用';
                            } else {
                                if (value == '0') {
                                    return  '<input class="tgl tgl-skewed" onclick="channelGain.onSwitchChange(' + row.channelGainId +',1 )" id="cb'+row.channelGainId+'" type="checkbox"><label class="tgl-btn" data-tg-off="启动" data-tg-on="禁用" for="cb'+row.channelGainId+'"></label>'
                                } else {
                                    return '<input class="tgl tgl-skeweds"  onclick="channelGain.onSwitchChange(' + row.channelGainId +',0 )" id="cb'+row.channelGainId+'" type="checkbox"> <label class="tgl-btn isok" data-tg-off="禁用" data-tg-on="启动" for="cb'+row.channelGainId+'"></label>'
                                }
                            }

                        }
                    },
                    {
                        field: 'gainType', title: '权益类型', align: 'center',
                        formatter: function (value, row, index) {
                            if (value == '0') {
                                return "新用户返点"
                            } else if (value == '1') {
                                return "复充返点"
                            } else {
                                return "尊享标识"
                            }
                        }
                    },
                    {field: 'sort', title: '排序', align: 'center'},
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '200', align: 'center',
                        formatter: function (value, row, index) {
                            if (row.channelLevel == 'S0') {
                                return '';

                            }
                            var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" mce_href="#" title="编辑" onclick="channelGain.edit(\''
                                + row.channelGainId + '\')">编辑</a> ';

                            var d = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" mce_href="#" title="删除" onclick="channelGain.deleteChannelGain(\''
                                + row.channelGainId + '\')">删除</a> ';

                            return a + d;
                        }
                    }
                ], onLoadSuccess: function () {

                }, onPageChange: function () {

                }
            });
    };

    function onSwitchChange (isId, state) {
        //修改操作
        $.ajax({
            type: "post",
            dataType: "json",
            async: false,
            url: prefix + "/updateChannelGainStatus",
            data: {
                status: state,
                id: isId
            },
            success: function (data) {
                reLoad();
            },
            error: function (xhr, error, exception) {
                let errorMsg = xhr.responseText;
            }
        });
    }


    function add() {
        location.href = prefix + "/add";
    }

    function edit(id) {
        location.href = prefix + "/edit/" + id;
    }


    function deleteChannelGain(id) {
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/del",
                type: "post",
                data: {
                    'id': id
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        $('#exampleTable').bootstrapTable('refresh'); //Table页面刷新
                    } else {
                        layer.msg(data.message);
                    }

                },
                error: function (xhr, error, exception) {
                    let errorMsg = xhr.responseText;
                    openMsg("error", "系统异常，" + errorMsg + "，请联系管理员！");
                }
            });
        })

    }

    return {
        init: init,
        reLoad: reLoad,
        add: add,
        edit: edit,
        onSwitchChange:onSwitchChange,
        exportList: exportList,
        deleteChannelGain: deleteChannelGain

    };
})();

var addChannelGain = (function () {
    function init() {

        validateRule();
    };

    function save() {
        var formData = new FormData($("#frm")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/saveChannelGain",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    javascript:history.back(-1);
                } else {
                    if (data.status == 600) {
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            }
        });
    };

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                channelLevel: {
                    required: true
                }, gainName: {
                    required: true
                }
            },
            messages: {
                channelLevel: {
                    required: icon + "请选择渠道商等级"
                }, gainName: {
                    required: icon + "请输入权益名称"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };
    return {
        init: init
    };


})();

var editChannelGain = (function () {
    function init() {

        validateRule();
    };

    function save() {
        var formData = new FormData($("#frm")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/saveChannelGain",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    javascript:history.back(-1);
                } else {
                    if (data.status == 600) {
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            }
        });
    };

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                channelLevel: {
                    required: true
                }, gainName: {
                    required: true
                }
            },
            messages: {
                channelLevel: {
                    required: icon + "请选择渠道商等级"
                }, gainName: {
                    required: icon + "请输入权益名称"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };
    return {
        init: init
    };


})();
